<?php

namespace app\index\logic\order;

use app\index\logic\BaseLogic;
use app\common\model\order\Order as OrderModel;
use think\facade\Db;
use think\facade\Log;

/**
 * 订单逻辑层
 * 处理订单相关的业务逻辑
 */
class OrderLogic extends BaseLogic
{
    /**
     * 订单模型实例
     * @var OrderModel
     */
    protected $orderModel;

    public function __construct()
    {
        $this->orderModel = new OrderModel();
    }

    /**
     * 获取用户订单列表
     * @param int $userId 用户ID
     * @param int $page 页码
     * @param int $limit 每页数量
     * @param string $status 订单状态
     * @return array
     */
    public function getUserOrders(int $userId, int $page = 1, int $limit = 10, string $status = '')
    {
        $query = $this->orderModel->where('user_id', $userId);

        if (!empty($status)) {
            $query->where('status', $status);
        }

        return $query->order('create_time', 'desc')
            ->page($page, $limit)
            ->select()
            ->toArray();
    }

    /**
     * 计算订单统计信息
     * @param int $userId 用户ID
     * @return array
     */
    public function getOrderStatistics(int $userId)
    {
        $statistics = [
            'total' => 0,
            'unpaid' => 0,
            'paid' => 0,
            'completed' => 0,
            'refunded' => 0,
        ];

        $statistics['total'] = $this->orderModel->where('user_id', $userId)->count();
        $statistics['unpaid'] = $this->orderModel->where('user_id', $userId)->where('status', 'unpaid')->count();
        $statistics['paid'] = $this->orderModel->where('user_id', $userId)->where('status', 'paid')->count();
        $statistics['completed'] = $this->orderModel->where('user_id', $userId)->where('status', 'completed')->count();
        $statistics['refunded'] = $this->orderModel->where('user_id', $userId)->where('status', 'refunded')->count();

        return $statistics;
    }

    /**
     * 检查订单是否可取消
     * @param int $orderId 订单ID
     * @param int $userId 用户ID
     * @return bool
     */
    public function canCancelOrder(int $orderId, int $userId): bool
    {
        $order = $this->orderModel->where('id', $orderId)->where('user_id', $userId)->find();

        if (empty($order)) {
            return false;
        }

        // 只有待支付状态的订单可以取消
        return $order['status'] === 'unpaid';
    }

    /**
     * 取消订单
     * @param int $orderId 订单ID
     * @param int $userId 用户ID
     * @return bool
     */
    public function cancelOrder(int $orderId, int $userId): bool
    {
        if (!$this->canCancelOrder($orderId, $userId)) {
            return false;
        }

        return $this->orderModel->where('id', $orderId)->update([
            'status' => 'cancelled',
            'update_time' => time()
        ]);
    }
}
